package org.wzl.todolisthelper.oss;

import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.wzl.todolisthelper.exception.BizException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.UUID;

@Slf4j
@Component
public class MinioUploadComp {

    @Value("${minio-bucket}")
    private String bucket;

    @Value("${minio-endpoint}")
    private String endpoint;


    @Resource
    private MinioClient minioClient;

    /**
     * base64格式图片上传
     * @return 返回图片的访问地址
     */
    public String upload(String base64Img, String fileName) {
        String uuid = UUID.randomUUID().toString();
        String name = uuid + fileName + ".png";
        try {
            // 获取系统临时目录
            String tempDir = System.getProperty("java.io.tmpdir");

            // 创建临时文件路径
            Path tempFilePath = Files.createTempFile(new File(tempDir).toPath(), bucket, ".png");
            this.convertBase64ToImage(base64Img, tempFilePath.toAbsolutePath().toString());
            minioClient.uploadObject(
                    UploadObjectArgs.builder().bucket(bucket).object(name).filename(tempFilePath.toAbsolutePath().toString()).build()
            );
            return String.format("%s/%s/%s", endpoint, bucket, name);
        } catch (Exception e) {
            log.error("minio 上传错误", e);
            throw new BizException("上传失败!,请联系管理页");
        }
    }

    private void convertBase64ToImage(String base64String, String outputFilePath) {
        try {
            // 解码 Base64 字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64String);

            // 写入文件
            try (OutputStream out = new FileOutputStream(outputFilePath)) {
                out.write(imageBytes);
            }
        } catch (Exception e) {
            log.error("转换 Base64 为图片时出错：{}", e.getMessage());
        }
    }

}
